package com.masterclient.app.modules.search.contract;

import com.eoner.baselib.container.CommonBaseResponse;
import com.eoner.baselib.presenter.ThrowableConsumer;
import com.masterclient.app.httpservice.RetrofitUtil2;
import com.masterclient.app.modules.search.beans.SearchResultDataBean;
import org.json.JSONException;
import org.json.JSONObject;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

/**
 * Created by TMVPHelper on 2017/07/18
 */
public class SearchResultPresenter extends SearchResultContract.Presenter {

    @Override
    public void getSearchResult(String page,String pageSize,String word) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("word",word);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<CommonBaseResponse<SearchResultDataBean>> observable = RetrofitUtil2.getInstance().getSearchResult(page,pageSize,body);
        Disposable disposable = toSubscribe(observable, (Consumer<CommonBaseResponse<SearchResultDataBean>>) bean -> {
            if (bean != null && 0 == bean.getCode()) {
                mView.getSearchResultSuccess(bean.data);
            } else {
                mView.getSearchResultFailed(bean.getMsg());
            }
        }, new ThrowableConsumer() {
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.getSearchResultFailed("网络异常，请重试");
            }
        });
        mRxManager.add(disposable);
    }
}